using MaterialSkin.Controls;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VideoAutoGenerator.UI.UserControls
{
    public partial class BatchProcessingControl : MaterialCard
    {
        private MaterialLabel titleLabel;
        private MaterialTextBox batchFolderTextBox;
        private MaterialButton batchFolderButton;
        private MaterialButton startBatchButton;
        private MaterialButton stopBatchButton;
        private MaterialListView fileListView;
        private Process currentProcess;

        public BatchProcessingControl()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 创建控件
            CreateControls();

            // 设置布局
            SetupLayout();

            // 添加事件处理程序
            SetupEventHandlers();

            this.ResumeLayout(false);
        }

        private void CreateControls()
        {
            titleLabel = new MaterialLabel();
            batchFolderTextBox = new MaterialTextBox();
            batchFolderButton = new MaterialButton();
            startBatchButton = new MaterialButton();
            stopBatchButton = new MaterialButton();
            fileListView = new MaterialListView();
        }

        private void SetupLayout()
        {
            // 设置控件属性
            this.AutoScroll = true;
            this.Dock = DockStyle.Fill;
            this.Padding = new Padding(20);

            // 标题
            titleLabel.Text = "批量处理";
            titleLabel.AutoSize = true;
            titleLabel.Font = new Font(titleLabel.Font.FontFamily, 16, FontStyle.Bold);
            titleLabel.Location = new Point(10, 10);

            // 批量处理目录
            var batchFolderLabel = new MaterialLabel();
            batchFolderLabel.Text = "处理目录:";
            batchFolderLabel.AutoSize = true;
            batchFolderLabel.Location = new Point(10, 50);

            batchFolderTextBox.Width = 400;
            batchFolderTextBox.Location = new Point(120, 48);

            batchFolderButton.Text = "浏览";
            batchFolderButton.Width = 70;
            batchFolderButton.Location = new Point(530, 48);

            // 按钮
            startBatchButton.Text = "开始处理";
            startBatchButton.Width = 100;
            startBatchButton.Location = new Point(120, 90);

            stopBatchButton.Text = "停止处理";
            stopBatchButton.Width = 100;
            stopBatchButton.Location = new Point(230, 90);
            stopBatchButton.Enabled = false;

            // 文件列表
            var fileListLabel = new MaterialLabel();
            fileListLabel.Text = "文件列表:";
            fileListLabel.AutoSize = true;
            fileListLabel.Location = new Point(10, 130);

            fileListView.Width = 550;
            fileListView.Height = 300;
            fileListView.Location = new Point(10, 160);
            fileListView.BorderStyle = BorderStyle.FixedSingle;
            fileListView.View = View.Details;
            fileListView.FullRowSelect = true;
            fileListView.GridLines = true;

            // 添加列
            fileListView.Columns.Add("文件名", 200);
            fileListView.Columns.Add("状态", 100);
            fileListView.Columns.Add("进度", 150);
            fileListView.Columns.Add("详情", 100);

            // 添加控件到面板
            this.Controls.Add(titleLabel);
            this.Controls.Add(batchFolderLabel);
            this.Controls.Add(batchFolderTextBox);
            this.Controls.Add(batchFolderButton);
            this.Controls.Add(startBatchButton);
            this.Controls.Add(stopBatchButton);
            this.Controls.Add(fileListLabel);
            this.Controls.Add(fileListView);
        }

        private void SetupEventHandlers()
        {
            batchFolderButton.Click += BatchFolderButton_Click;
            startBatchButton.Click += StartBatchButton_Click;
            stopBatchButton.Click += StopBatchButton_Click;
        }

        private void BatchFolderButton_Click(object sender, EventArgs e)
        {
            using (var folderBrowserDialog = new FolderBrowserDialog())
            {
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    batchFolderTextBox.Text = folderBrowserDialog.SelectedPath;
                    LoadFilesFromFolder(folderBrowserDialog.SelectedPath);
                }
            }
        }

        private void LoadFilesFromFolder(string folderPath)
        {
            fileListView.Items.Clear();

            try
            {
                // 查找MP3文件
                string[] mp3Files = Directory.GetFiles(folderPath, "*.mp3");
                
                foreach (string mp3File in mp3Files)
                {
                    string fileName = Path.GetFileNameWithoutExtension(mp3File);
                    string datFile = Path.Combine(folderPath, fileName + ".dat");
                    
                    var item = new ListViewItem(fileName);
                    item.SubItems.Add(File.Exists(datFile) ? "待处理" : "缺少DAT");
                    item.SubItems.Add("");
                    item.SubItems.Add(mp3File);
                    
                    fileListView.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文件列表时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void StartBatchButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(batchFolderTextBox.Text) || !Directory.Exists(batchFolderTextBox.Text))
            {
                MessageBox.Show("请选择有效的处理目录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (fileListView.Items.Count == 0)
            {
                MessageBox.Show("目录中没有找到可处理的文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 禁用开始按钮，启用停止按钮
            startBatchButton.Enabled = false;
            stopBatchButton.Enabled = true;

            try
            {
                // 调用 Node.js 批量处理脚本
                await RunBatchNodeJsScript(batchFolderTextBox.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量处理过程中出现错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                startBatchButton.Enabled = true;
                stopBatchButton.Enabled = false;
            }
        }

        private async Task RunBatchNodeJsScript(string folderPath)
        {
            var processStartInfo = new ProcessStartInfo
            {
                FileName = "node",
                Arguments = $"run_video_batch.js \"{folderPath}\"",
                WorkingDirectory = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\.."),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            try
            {
                currentProcess = new Process { StartInfo = processStartInfo };
                
                // 事件处理程序用于捕获输出
                currentProcess.OutputDataReceived += (sender, e) => {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        UpdateBatchLog(e.Data);
                    }
                };

                currentProcess.ErrorDataReceived += (sender, e) => {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        UpdateBatchLog($"[错误] {e.Data}");
                    }
                };

                // 启动进程
                currentProcess.Start();

                // 开始异步读取输出
                currentProcess.BeginOutputReadLine();
                currentProcess.BeginErrorReadLine();

                // 等待进程结束
                await Task.Run(() => currentProcess.WaitForExit());
            }
            catch (Exception ex)
            {
                throw new Exception($"无法启动 Node.js 批量处理进程: {ex.Message}");
            }
            finally
            {
                currentProcess?.Dispose();
                currentProcess = null;
            }
        }

        private void UpdateBatchLog(string message)
        {
            if (fileListView.InvokeRequired)
            {
                fileListView.Invoke(new Action<string>(UpdateBatchLog), message);
            }
            else
            {
                // 这里可以更新文件列表中的状态
                // 简化实现，实际应用中可以根据输出信息更新具体文件的状态
                Console.WriteLine(message);
            }
        }

        private void StopBatchButton_Click(object sender, EventArgs e)
        {
            if (currentProcess != null && !currentProcess.HasExited)
            {
                try
                {
                    currentProcess.Kill();
                    MessageBox.Show("批量处理已被用户终止", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法停止进程: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}